<template>
  <div class="main-box">
    <div class="form-header">
      <i class="title-font">录入信息</i>
    </div>
    <div class="form-body">
      <el-form
        class="troila-form"
        :label-width="formLabelWidth"
        :model="form"
        :rules="rules"
        ref="form"
      >
        <div class="form-box">
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="form.roleName"
              auto-complete="off"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
          <el-form-item label="权限字符" prop="roleCode">
            <el-input
              v-model="form.roleCode"
              auto-complete="off"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
          <el-form-item label="显示顺序" prop="roleSort">
            <el-input
              v-model="form.roleSort"
              auto-complete="off"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              auto-complete="off"
              placeholder="请输入内容"
              type="textarea"
              rows="4"
              maxlength="100"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item
            label="角色状态"
            prop="state"
            v-if="$route.name == 'editRole'"
          >
            <el-radio-group v-model="form.state">
              <el-radio
                :label="item.dictCode"
                v-for="item in dictionary.userStatus"
                :key="item.dictCode"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item class="btn-box">
            <el-button @click="cancel">{{
              ajaxIng ? '返 回' : '取 消'
            }}</el-button>
            <el-button type="primary" :loading="ajaxIng" @click="submitForm"
              >确 定</el-button
            >
          </el-form-item>
        </div>
        <div class="form-box">
          <el-form-item label="菜单权限" prop="menus">
            <div class="el-input__inner roleTree">
              <el-scrollbar v-if="list && list.length > 0">
                <el-tree
                  @check="getCheck"
                  :data="list"
                  show-checkbox
                  node-key="id"
                  :default-expanded-keys="openKeys"
                  :default-checked-keys="form.menus"
                  check-strictly
                  ref="tree"
                  :props="{
                    label: 'menuName',
                  }"
                ></el-tree>
                <!-- expand-on-click-node 是否在点击节点的时候展开或者收缩节点 -->
                <!-- check-on-click-node 是否在点击节点的时候选中节点 -->
              </el-scrollbar>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
export default {
  name: 'roleForm',
  data() {
    return {
      form: {
        roleName: '',
        roleCode: '',
        roleSort: '',
        remark: '',
        state: '',
        menus: [],
      },
      formLabelWidth: '100px', //标题文字宽度
      rules: {
        // 规则
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        roleCode: [
          { required: true, message: '请输入权限字符', trigger: 'blur' },
        ],
        state: [
          { required: true, message: '请选择角色状态', trigger: 'change' },
        ],
        menus: [{ required: true, message: '请选择菜单', trigger: 'change' }],
      },
      dictionary: {
        // 字典信息
        sex: [
          { dictName: '男', dictCode: '1' },
          { dictName: '女', dictCode: '2' },
        ],
        userStatus: [
          { dictName: '启用', dictCode: '1' },
          { dictName: '停用', dictCode: '0' },
        ],
        roleList: [
          { dictName: '角色1', dictCode: '1' },
          { dictName: '角色2', dictCode: '2' },
          { dictName: '角色3', dictCode: '3' },
          { dictName: '角色4', dictCode: '4' },
          { dictName: '角色5', dictCode: '5' },
        ],
      },
      list: [],
      ajaxIng: false,
    }
  },
  computed: {
    openKeys() {
      // console.log(this.list.map((v) => v.id))
      return this.list.map((v) => v.id)
    },
  },
  watch: {},
  methods: {
    getMenuList() {
      this.API.menuManage
        .pageList({
          pageNum: 1,
          pageSize: 99999,
        })
        .then((res) => {
          if (res.code == 1) {
            this.list = this.toFilters(res.data.records)
            let list = []
            this.list.map((v) => {
              list = [...list, ...this.recursion(v)]
            })
            this.form.menus = this.form.menus.filter(
              (item) => list.indexOf(item) > -1
            )
          }
        })
    },
    toFilters(list) {
      return list.filter((item) => {
        item.children && item.children.length > 0
          ? (item.children = this.toFilters(item.children))
          : null
        item.children.map((v) => {
          v.parent = item
        })
        return item.menuStatus != '0'
      })
    },
    getCheck(item, choose) {
      // console.log(
      //   item,
      //   choose,
      //   this.form.menus,
      //   this.$refs.tree.getCheckedNodes()
      // )
      let chooseItem = [...this.$refs.tree.getCheckedNodes()]
      let child = this.getChildren(item)
      let childKeys = child.map((v) => v.id)
      choose.checkedKeys.indexOf(item.id) > -1
        ? (chooseItem = chooseItem.concat(child))
        : (chooseItem = chooseItem.filter((v) => childKeys.indexOf(v.id) == -1))
      let chooseMenu = chooseItem.map((v) => v.id)
      if (chooseMenu.indexOf(item.id) > -1) {
        chooseMenu = chooseMenu.concat(this.getParents(item, chooseMenu))
      } else {
      }
      this.form.menus = [...chooseMenu]
      // this.form.menus.indexOf(item.id) > -1 &&
      // this.form.menus.indexOf(item.parentId) == -1
      //   ? this.form.menus.push(item.parentId)
      //   : null
      this.$refs.tree.setCheckedKeys(this.form.menus)
      // console.log(this.form.menus)
      this.$nextTick((v) => {
        this.$refs.form.validateField('menus')
      })
    },
    getParents(item, list) {
      let arr = []
      if (item.parentId != '0') {
        if (list.indexOf(item.parentId) == -1) {
          arr.push(item.parentId)
        }
        arr = [...arr, ...this.getParents(item.parent, list)]
      }
      return arr
    },
    getChildren(item) {
      let arr = []
      if (item.children && item.children.length > 0) {
        arr = [...item.children]
        for (let i in item.children) {
          arr = [...arr, ...this.getChildren(item.children[i])]
        }
      }
      return arr
    },
    cancel() {
      this.$router.back(-1)
    },
    submitForm() {
      if (this.ajaxIng) {
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.ajaxIng = true
          if (this.roleId) {
            let postData = {
              id: this.roleId,
              roleName: this.form.roleName,
              roleCode: this.form.roleCode,
              roleSort: this.form.roleSort,
              remark: this.form.remark,
              menuId: this.form.menus.join(','),
              state: this.form.state,
            }
            this.API.roleManage
              .updateRole(postData)
              .then((res) => {
                this.ajaxIng = false
                if (res.code == 1) {
                  this.$alertFn.success('修改角色成功')
                  this.cancel()
                }
              })
              .catch((err) => {
                this.ajaxIng = false
              })
          } else {
            let postData = {
              roleName: this.form.roleName,
              roleCode: this.form.roleCode,
              roleSort: this.form.roleSort,
              remark: this.form.remark,
              menuId: this.form.menus.join(','),
            }
            this.API.roleManage
              .addRole(postData)
              .then((res) => {
                this.ajaxIng = false
                if (res.code == 1) {
                  this.$alertFn.success('新建角色成功')
                  this.cancel()
                }
              })
              .catch((err) => {
                this.ajaxIng = false
              })
          }
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
  },
  created() {
    this.getMenuList()
    if (this.$route.name == 'editRole') {
      this.roleId = this.decode(this.$route.params.roleId)
      this.roleId ? null : this.cancel()
      try {
        for (let k in this.$route.params.row) {
          this.form[k] = this.$route.params.row[k]
        }
        this.form.menus = this.$route.params.row.menuIdList
      } catch (error) {
        this.cancel()
      }
    }
  },
}
</script>
<style  scoped>
.main-box {
  padding: 21px 22px 0 20px;
}
.form-box {
  width: 50%;
  display: inline-block;
  vertical-align: top;
  box-sizing: border-box;
}
.roleTree {
  height: 300px !important;
  width: 300px;
  padding: 5px 0;
}
.roleTree > div {
  height: 100%;
}
</style>